<template>
  <div>
    <div class="page-header">
      <div class="box">
        <el-row class="left">
          <el-row class="title">
            <span></span>
            竞价报备详情
          </el-row>
        </el-row>
        <el-row class="right">
          <el-button type="primary" class="tlwok-btn" @click="reloadPage">
            <span class="el-icon-refresh el-icon--left"></span>刷新
          </el-button>
          <el-button type="danger" class="tlwok-btn" @click="closePage">
            <span class="el-icon-close el-icon--left"></span>关闭
          </el-button>
        </el-row>
      </div>
    </div>
    <div class="page-content">
      <div class="info-box">
        <el-steps v-if="stepList[stepActive]" :active="stepActive" finish-status="success" :process-status="stepList[stepActive].status==1?'success':(stepList[stepActive].status==2?'error':'process')" align-center>
          <el-step v-for="step in stepList" :key="step.code" icon="el-icon-time" :title="step.desc" :description="descTime(step.code,basicInfo.filingState)"></el-step>
        </el-steps>
      </div>
      <div class="table-box">
        <div class="table-title">
          <el-row class="left">
            <span class="title">报备编号：{{basicInfo.filingNumber||basicInfo.filingBidId}}</span>
            <span class="warning-text">
              <i class="el-icon-warning"></i>
              状态：{{basicInfo.filingState | statusListC1_b}}
            </span>
          </el-row>
          <el-button class="filing-button" type="primary" v-if="fromOSS" @click="exportExcel">Excel导出</el-button>
        </div>
        <div class="info-item base-info">
          <div class="thead">
            <el-row>
              <i class="el-icon-s-management el-icon--left"></i> 报备基础信息
            </el-row>
          </div>
          <div class="tbody">
            <div class="content">
              <div class="line-item">
                <el-row>
                  <span class="required-icon">*</span>
                  报备人姓名：{{basicInfo.registrarName}}
                </el-row>
                <el-row>
                  <span class="required-icon">*</span>
                  竞价平台：{{basicInfo.bidPlatformName}}
                </el-row>
              </div>
              <div class="line-item">
                <el-row>
                  <span class="required-icon">*</span>
                  报备人电话：{{basicInfo.registrarPhone}}
                </el-row>
                <el-row>
                  <span class="required-icon">*</span>
                  竞价截止时间：{{basicInfo.bidEndTime | dateFilter}}
                </el-row>
              </div>
              <div class="line-item">
                <el-row>
                  <span class="required-icon">*</span>
                  项目编号：{{basicInfo.projectId}}
                </el-row>
                <el-row>
                  <span class="required-icon">*</span>
                  报价链接：
                  <a class="link" :href="basicInfo.bidUrl">{{basicInfo.bidUrl}}</a>
                </el-row>
              </div>
              <div class="line-item">
                <el-row>备注：{{basicInfo.remark || '无'}}</el-row>
              </div>
            </div>
          </div>
        </div>
        <div class="info-item countdown">
          <span class="desc">竞价结束倒计时：</span>
          <div class="time">{{countDownText}}</div>
        </div>
        <div class="info-item product-info">
          <div class="thead">
            <el-row>
              <i class="el-icon-s-management el-icon--left"></i> 报备商品信息
            </el-row>
            <el-row class="info">
              共报备
              <span class="warning-text">{{tableObj.goodSkuNum || 0}}条&nbsp;</span>商品，合计数量
              <span class="warning-text">{{goodNumActive}}</span>，合计总价
              <span class="warning-text">{{goodTotalPriceActive.toFixed(2) }}元</span>
            </el-row>
          </div>
          <el-table border :data="tableObj.tableData" style="width: 100%" max-height="400" ref="table">
            <el-table-column align="center" label="序号" width="80">
              <template slot-scope="scope">{{scope.$index+1+(currentPage-1)*currentSize}}</template>
            </el-table-column>
            <el-table-column align="center" prop="goodBrand" label="品牌" width="100"></el-table-column>
            <el-table-column align="center" prop="goodName" label="商品名称"></el-table-column>
            <el-table-column align="center" prop="goodModel" label="型号" width="160"></el-table-column>
            <el-table-column align="center" prop="num" label="数量" width="90">
              <template slot-scope="scope">
                <el-input v-if="type==1" v-model="scope.row.num"></el-input>
                <span v-else>{{scope.row.num}}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="unit" label="单位" width="80"></el-table-column>
            <el-table-column align="center" prop="price" label="单价(元)" width="100">
              <template slot-scope="scope">
                <el-input v-if="type==1" v-model="scope.row.price"></el-input>
                <span v-else>{{scope.row.price }}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="totalPrice" label="总价(元)" width="120">
              <template slot-scope="scope">
                <span v-if="type==1">{{scope.row.price*100*parseInt(scope.row.num)/100}}</span>
                <span v-else>{{scope.row.totalPrice}}</span>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination v-if="type!=1" class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="pageSizeArr" :page-size="currentSize" layout="total, sizes, prev, pager, next, jumper" :total="tableObj.goodSkuNum"></el-pagination>
        </div>
        <div class="btn-box" v-if="type===1&&tableObj.tableData.length>0">
          <el-button type="primary" plain @click="resetTable()">重置</el-button>
          <el-button type="primary" @click="submitTable()">提交修改</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'FilingDetail',
  data() {
    return {
      type: 0, //0:查看  1：修改
      fromOSS: true,
      tableObj: { tableData: [], goodSkuNum: 0, goodNum: 0 },
      basicTableData: {}, //tableObj的初始数据备份，修改信息时用
      id: null,
      basicInfo: {},
      stepList: [
        { code: 0, desc: '提交审核', status: 0 },
        { code: 1, desc: '平台审核', status: 0 },
        { code: 2, desc: '平台报价', status: 0 },
        { code: 3, desc: '竞价结束', status: 0 },
      ],
      goodTotalPrice: 0,
      currentSize: 10,
      currentPage: 1,
      pageSizeArr: [10, 20, 30, 40],
      countDownText: '倒计时加载中……',
      deadline: 1591005540000,
    }
  },
  computed: {
    stepActive() {
      let val = this.basicInfo.filingState
      switch (val) {
        case 4:
          val = 3
          this.stepList[val].desc = '竞价成功'
          this.stepList[val].status = 1
          break
        case 5:
          val = 3
          this.stepList[val].desc = '竞价失败'
          this.stepList[val].status = 2
          break
        case 6:
          val = 1
          this.stepList[val].desc = '审核未通过'
          this.stepList[val].status = 2
          break
        case 7:
          val = 0
          this.stepList[val].desc = '已取消报备'
          this.stepList[val].status = 2
          break

        default:
          break
      }
      return val
    },
    goodNumActive() {
      let num = 0
      if (this.type == 1) {
        this.tableObj.tableData.map(item => {
          num += parseInt(item.num) || 0
        })
      } else {
        num = this.tableObj.goodNum
      }
      return num || 0
    },
    goodTotalPriceActive() {
      let total = 0
      if (this.type == 1) {
        this.tableObj.tableData.map(item => {
          item.num = parseInt(item.num) || 0
          total += (item.price * 1000 * item.num) / 1000
        })
      } else {
        total = this.goodTotalPrice
      }

      return total || 0
    },
  },
  created() {
    this.type = parseInt(this.$route.query.type) || 0
    this.id = this.$route.query.id
    // if (this.$route.name.indexOf('OSS') > -1) this.fromOSS = true
  },
  methods: {
    reloadPage() {
      location.reload()
    },
    closePage() {
      if (this.type == 1) {
        let path = ''
        if (this.fromOSS) path = 'OSSFilings'
        else path = 'MyFiling'

        this.$router.push({ path: path, query: { filingType: 1 } })
      } else {
        window.close()
      }
    },
    /**
     * 获取基础信息
     */
    getBasicInfo() {
      let path = '/api/manage/audit/queryBidFilingAuditDetail'

      this.$axios.get(`${path}?id=${this.id}`).then(res => {
        if (res.success) {
          this.basicInfo = res.result

          this.goodTotalPrice = this.basicInfo.goodTotalPrice
          this.tableObj.goodSkuNum = this.basicInfo.goodSkuNum
          this.tableObj.goodNum = this.basicInfo.goodNum

          this.deadline = this.basicInfo.bidEndTime
          this.countDown()
        } else this.$message.error(res.desc)
      })
    },
    /**
     * 获取商品信息
     */
    getGoodsInfo() {
      if (this.type == 1) {
        this.$axios
          .get(`/api/bid/modifyBFilingGoodsInfo/${this.id}`)
          .then(res => {
            if (res.success) {
              this.tableObj.tableData = res.result.filingBidGoodsInfo.list
              this.tableObj.tableData.map(item => {
                item.num = parseInt(item.num)
              })

              // 留备份数据
              this.basicTableData = Object.assign(
                [],
                JSON.parse(JSON.stringify(this.tableObj.tableData))
              )
            } else this.$message.error(res.desc)
          })
      } else {
        let path = this.fromOSS
          ? '/api/manage/audit/queryBidFilingAuditGoodsList'
          : `/api/myFiling/getBidFilingGoodsInfo`
        this.$axios
          .get(
            `${path}?id=${this.id}&size=${this.currentSize}&startPage=${this.currentPage}`
          )
          .then(res => {
            if (res.success) {
              this.tableObj.tableData = res.result.filingBidGoodsPageResult.list
            } else this.$message.error(res.desc)
          })
      }
    },
    /**
     * 切换每页显示条数
     */
    handleSizeChange(val) {
      this.currentSize = val
      this.currentPage = 1
      this.getGoodsInfo()
    },
    /**
     * 翻页
     */
    handleCurrentChange(val) {
      this.currentPage = val
      this.getGoodsInfo()
    },
    exportExcel() {
      window.location.href =
        window.globalConfig.apiUrl +
        '/api/manage/exportBidFilingInfo?id=' +
        this.id
    },
    /**
     * 步骤图展示
     */
    descTime(step, status) {
      if (
        (status > 6 && step > 0) ||
        (status > 5 && step > 1) ||
        step > status - 1
      )
        return null

      let time = ''
      switch (parseInt(step)) {
        case 0:
          time =
            status == 7 ? this.basicInfo.updateTime : this.basicInfo.createTime
          break
        case 1:
          time = this.basicInfo.platformAuditTime
          break
        case 2:
          time = this.basicInfo.platformQuoteTime
          break

        default:
          time = this.basicInfo.updateTime
          break
      }
      return this.formatDate(time)
    },
    // 倒计时
    countDown() {
      if (this.basicInfo.filingState > 5) {
        this.countDownText = '停止报备'
        return
      }

      let nowtime = new Date().getTime()
      let lefttime = parseInt((this.deadline - nowtime) / 1000)
      let d = parseInt(lefttime / (24 * 60 * 60))
      let h = parseInt((lefttime / (60 * 60)) % 24)
      let m = parseInt((lefttime / 60) % 60)
      let s = parseInt(lefttime % 60)

      d = this.addZero(d)
      h = this.addZero(h)
      m = this.addZero(m)
      s = this.addZero(s)

      this.countDownText = `${d}天 ${h} 时 ${m} 分 ${s} 秒`
      if (lefttime <= 0) {
        this.countDownText = '倒计时结束'
        return
      } else {
        setTimeout(this.countDown, 1000)
      }
    },
    addZero(i) {
      return i < 10 ? '0' + i : i + ''
    },
    /**
     * 提交报备信息修改
     */
    submitTable() {
      let arr = []
      let _tableData = this.tableObj.tableData
      _tableData.map((item, i) => {
        if (
          !(
            parseInt(item.num) === parseInt(this.basicTableData[i].num) &&
            parseFloat(item.price) === parseFloat(this.basicTableData[i].price)
          )
        )
          arr.push(i)
      })
      if (arr.length < 1) {
        this.$message.error('还未修改任何信息')
        return
      }
      let numberReg = /^[1-9]\d*$/
      let priceReg = /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/
      for (let index = 0; index < _tableData.length; index++) {
        let item = _tableData[index]
        if (!numberReg.test(item.num + '')) {
          this.$message.error('请输入正确的商品数量')
          return
        }
        if (!priceReg.test(item.price + '')) {
          this.$message.error('请输入正确的单价，并保留两位小数')
          return
        }
      }
      this.$axios.post('/api/bid/updateBidFiling', _tableData).then(res => {
        if (res.success) {
          this.$message({
            type: 'success',
            message: '报备商品信息修改成功',
          })
        } else this.$message.error(res.desc)
      })
    },
    resetTable() {
      this.tableObj.tableData = Object.assign(
        [],
        JSON.parse(JSON.stringify(this.basicTableData))
      )
    },
  },
  mounted() {
    this.getBasicInfo()
    this.getGoodsInfo()
  },
}
</script>

<style lang="less" scoped>
.page-header {
  background: #eee;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 10;
  .box {
    margin: auto;
    width: 1440px;
    height: 65px;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 38px;
  }
  .title {
    font-size: 16px;
    font-weight: bold;
    span {
      width: 0;
      height: 20px;
      border: 2px solid #1abc9c;
      background: #1abc9c;
      margin-right: 14px;
    }
  }
}
.page-content {
  background: #fff;
  padding-top: 65px;
}
.info-box {
  margin: 30px auto;
  width: 60%;
}
.table-box,
.btn-box {
  width: 1078px;
  margin: 20px auto;
}
.table-title {
  border: 1px solid #bbb;
  padding: 0 25px;
  height: 45px;
  display: flex;
  align-items: center;
  background: #e4e4e4;
  justify-content: space-between;
  .left {
    display: flex;
  }
  .title {
    font-weight: bold;
    margin-right: 50px;
  }
}
.info-item {
  border: 1px solid #bbb;
  border-top: 0;
  .thead {
    background: #f5f5f5;
    padding: 0 25px;
    height: 45px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-weight: bold;
    .info {
      margin-right: 100px;
    }
  }
}
.base-info {
  .tbody {
    border-top: 1px solid #bbb;
    padding: 25px;
  }
  .content {
    width: 85%;
    margin: 0 auto;
  }
  .line-item {
    display: flex;
    align-items: flex-start;
    .el-row {
      flex: 1;
      margin-bottom: 12px;
      line-height: 28px;
      &:first-child {
        margin-right: 50px;
      }
    }
  }
}
.btn-box {
  text-align: right;
  .el-button {
    width: 98px;
  }
}
.dialog-form {
  .el-input {
    width: 250px;
    margin: auto;
  }
  .warning-text {
    margin-left: 10px;
    font-size: 13px;
  }
}
.link {
  color: #1abc9c;
  text-decoration: underline;
}
.countdown {
  background-color: #f5f5f5;
  padding: 20px 25px;
  display: flex;
  align-items: center;
  .desc {
    font-weight: bold;
  }
  .time {
    margin-left: 30px;
    font-size: 24px;
    color: red;
  }
}
.pagination {
  text-align: right;
  padding: 10px 20px;
}
</style>
